from django.apps import AppConfig
import time
from .views import MQTTService
import atexit


class MqttDataPushConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "ephm_mqtt_data_push"

    mqtt_service = None

    def ready(self):
        # 避免Django的自动重载机制触发ready方法调用（开发环境中修改代码保存等）
        import os

        if os.environ.get("RUN_MAIN") == "true":
            print(os.environ.get("RUN_MAIN"))
            print("自动重载机制下运行，跳过MQTT服务启动")
            return

        # 初始化 MQTT 服务
        self.mqtt_service = MQTTService()
        self.mqtt_service.client.loop_start()

        # 注册清理函数，在程序退出时停止 MQTT 服务
        atexit.register(self.stop_mqtt_service)

    def stop_mqtt_service(self):
        if self.mqtt_service:
            print("停止 MQTT 服务")
            self.mqtt_service.client.loop_stop()
            self.mqtt_service.client.disconnect()
